package com.ruoyi.project.data.controller;

import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.project.data.domain.WeightStation;
import com.ruoyi.project.data.service.IWeightStationService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictDataService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.data.domain.WeightWorker;
import com.ruoyi.project.data.service.IWeightWorkerService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 人员信息Controller
 *
 * @author ruoyi
 * @date 2020-03-21
 */
@RestController
@RequestMapping("/system/worker")
public class WeightWorkerController extends BaseController
{
    @Autowired
    private IWeightWorkerService weightWorkerService;
    @Autowired
    private IWeightStationService weightStationService;
    @Autowired
    private PermissionService permissionService;


    /**
     * 查询人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:list')")
    @GetMapping("/list")
    public TableDataInfo list(WeightWorker weightWorker)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        weightWorker.setStationId(stationId);
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        weightWorker.setAreas(areas);
        weightWorker.setManagementCharacters(managementCharacters);
        startPage();
        List<WeightWorker> list = weightWorkerService.selectWeightWorkerList(weightWorker);
        return getDataTable(list);
    }

    /**
     * 导出人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:export')")
    @Log(title = "人员信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(WeightWorker weightWorker)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        weightWorker.setStationId(stationId);
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        weightWorker.setAreas(areas);
        weightWorker.setManagementCharacters(managementCharacters);
        List<WeightWorker> list = weightWorkerService.selectWeightWorkerList(weightWorker);
        ExcelUtil<WeightWorker> util = new ExcelUtil<WeightWorker>(WeightWorker.class);
        return util.exportExcel(list, "worker");
    }

    /**
     * 获取人员信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

        WeightWorker worker = weightWorkerService.selectWeightWorkerById(id);
        return AjaxResult.success(worker);
    }

    /**
     * 新增人员信息
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:add')")
    @Log(title = "人员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WeightWorker weightWorker)
    {
        if (UserConstants.NOT_UNIQUE.equals(weightWorkerService.checkWorkerPhoneUnique(weightWorker)))
        {
            return AjaxResult.error("新增人员失败，手机号已存在");
        }
        if(weightWorker.getIdCard() != null && !"".equals(weightWorker.getIdCard())){
            if (UserConstants.NOT_UNIQUE.equals(weightWorkerService.checkWorkerIdCardUnique(weightWorker)))
            {
                return AjaxResult.error("新增人员失败，身份证号已存在");
            }
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station")
                || permissionService.hasRole("xq_station") || permissionService.hasRole("jy_station") || permissionService.hasRole("yx_station"))){
            Long stationId = user.getStationId();
            weightWorker.setStationId(stationId);
        }
        if(weightWorker.getPermissions() == null || "".equals(weightWorker.getPermissions())){
            return AjaxResult.error("请选择人员权限");
        }
        String[] permissionsArray = weightWorker.getPermissions().split(",");
        if(permissionsArray == null || permissionsArray.length == 0){
            return AjaxResult.error("请选择人员权限");
        }
        if(permissionsArray != null && permissionsArray.length > 1) {
            // 判断该人员所属场站设置的权限
            WeightStation station = weightStationService.selectWeightStationById(weightWorker.getStationId());
            if(station == null) {
                return AjaxResult.error("人员所属场站不存在");
            }
            if("0".equals(station.getIsAllPermissions())) {
                return AjaxResult.error("所选场站人员只能选择一个权限");
            }
        }
        if(weightWorker.getPassword() != null && !"".equals(weightWorker.getPassword())) {
            weightWorker.setPassword(Md5Utils.hash(weightWorker.getPassword()));
        }
        weightWorker.setCreateId(user.getUserId().toString());
        weightWorker.setCreateTime(DateUtils.getNowDate());
        return toAjax(weightWorkerService.insertWeightWorker(weightWorker));
    }

    /**
     * 修改人员信息
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:edit')")
    @Log(title = "人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WeightWorker weightWorker)
    {
        if (UserConstants.NOT_UNIQUE.equals(weightWorkerService.checkWorkerPhoneUnique(weightWorker)))
        {
            return AjaxResult.error("编辑人员失败，手机号已存在");
        }
        if(weightWorker.getIdCard() != null && !"".equals(weightWorker.getIdCard())) {
            if (UserConstants.NOT_UNIQUE.equals(weightWorkerService.checkWorkerIdCardUnique(weightWorker))) {
                return AjaxResult.error("编辑人员失败，身份证号已存在");
            }
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station")
                || permissionService.hasRole("xq_station") || permissionService.hasRole("jy_station") || permissionService.hasRole("yx_station"))){
            Long stationId = user.getStationId();
            weightWorker.setStationId(stationId);
        }
        if(weightWorker.getPermissions() == null || "".equals(weightWorker.getPermissions())){
            return AjaxResult.error("请选择人员权限");
        }
        String[] permissionsArray = weightWorker.getPermissions().split(",");
        if(permissionsArray == null || permissionsArray.length == 0){
            return AjaxResult.error("请选择人员权限");
        }
        if(permissionsArray != null && permissionsArray.length > 1) {
            // 判断该人员所属场站设置的权限
            WeightStation station = weightStationService.selectWeightStationById(weightWorker.getStationId());
            if(station == null) {
                return AjaxResult.error("人员所属场站不存在");
            }
            if("0".equals(station.getIsAllPermissions())) {
                return AjaxResult.error("所选场站人员只能选择一个权限");
            }
        }
        weightWorker.setUpdateId(user.getUserId().toString());
        weightWorker.setUpdateTime(DateUtils.getNowDate());
        return toAjax(weightWorkerService.updateWeightWorker(weightWorker));
    }

    /**
     * 修改密码
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:password')")
    @Log(title = "人员信息", businessType = BusinessType.UPDATE)
    @PutMapping("/modifyPassword")
    public AjaxResult modifyPassword(@RequestBody WeightWorker weightWorker)
    {
        if(weightWorker.getPassword() != null && !"".equals(weightWorker.getPassword())) {
            weightWorker.setPassword(Md5Utils.hash(weightWorker.getPassword()));
        }
        return toAjax(weightWorkerService.modifyPassword(weightWorker));
    }

    /**
     * 删除人员信息
     */
    @PreAuthorize("@ss.hasPermi('weight:worker:remove')")
    @Log(title = "人员信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(weightWorkerService.deleteWeightWorkerByIds(ids));
    }
}
